define(function(require, exports, module) {

  var Backbone = require('backbone');
  var $ = require('jquery');
  var _ = require('underscore');
  var jsonview = require('jsonview');
  var tmpl = require('text!../tmpl.html')
  var count = require('hy5b/count/index')

  function main() {
    var $app = $('<div id="app">');
    $('#main').html($app);

    var $el = $("<div>");

    $app.append(tmpl).append($el)

    switch (1) {
      case 1:
        SocketIoClientInstance($el);
        break;
      case 2:
        NativeWebsocketClientInstance()
        break;
      // case 3:
      //   NativeWebsocketClientInstance()
      //   break;
    }
  }

  function NativeWebsocketClientInstance() {
    
    // var url = 'wss://show.uyuntest.cn/api/ws/dataset';
    var websocketClient = new WebSocket('ws://localhost:10000/api/ws/dataset');
    // Connection opened
    websocketClient.addEventListener('open', function (event) {
        console.log('socket open: ', event)
        websocketClient.send('Hello Server!');
    });
    // Listen for messages
    websocketClient.addEventListener('message', function (event) {
        console.log('socket receive message: ', event.data);
    });

    websocketClient.onclose = function(event) {
      console.log('socket close: ', event);
    }

    websocketClient.onerror = function(event) {
      console.log('socket error: ', event);
    }
  }

  function SocketIoClientInstance($el) {

    var io = require('io');

    var socket = io.connect('ws://localhost:7700', {
      path: '/localws',
      reconnection: true
    });

    socket.on('push', function (data) {
      console.log(data);
      socket.emit('push_ack', { status: 0 });
    });

    var isFirstConnect = true;

    socket.on('connect', () => {
      console.warn('websocket is connected', arguments)
      if (!isFirstConnect) {
        //重连要干麻
      }
      isFirstConnect = false
    })

    socket.on('disconnect', () => { //服务端停止的时候，客户端收到一个disconnect事件
      console.warn('websocket receive disconnect', arguments)
      // socket.disconnect();  //只要前后端有一个执行了disconnect,重连机制便不再生效，所以不能在这里执行disconnect
    })

    socket.on('receive', data => {
      console.log('receive sth');
      $el.append(data + '<br />')
    })

    $('#add').click(function() {
      socket.emit('add', count())
    })

    $('#disconnect').click(function() {
      socket.emit('disconnection')
      socket.disconnect() //当前端手动disconnect，即使后端不执行disconnect，前端也不会尝试重连
    })
  }

  return main;
})
